package com.flycms.web.system.rest;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PagingParam;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.offline.model.OfflineActivity;
import com.flycms.module.offline.model.OfflineActivitySignUp;
import com.flycms.module.offline.model.OfflineActivityStatus;
import com.flycms.module.offline.service.OfflineActivityService;
import com.flycms.module.offline.service.OfflineActivitySignUpService;
import com.flycms.web.front.rest.OfflineActivityController;

@RestController
@RequestMapping("/system/oa")
public class AdminOfflineController extends BaseController {
    
private static final Logger logger = LogManager.getLogger(OfflineActivityController.class);
    
    @Autowired
    protected OfflineActivityService offlineService;
    
    @Autowired
    protected OfflineActivitySignUpService signUpService;
    
    @PostMapping(value = {"/add"})
    public RestDataVo addOfflineActivity(@Valid @RequestBody OfflineActivity offline, BindingResult errors) {
        RestDataVo rest = null;
        String validResult = CommonUtils.validParams(errors, logger);
        if (StringUtils.isNotEmpty(validResult)) {
            return RestDataVo.ERROR(validResult);
        }
        if (offline.getStartTime().after(offline.getEndTime())) {
            return RestDataVo.ERROR("线下活动开始时间在结束时间之后");
        }
//        Long userId = getAdminUserId();
        try {
            offline.setStatus(OfflineActivityStatus.ACTIVITY_SIGNING.value());
            offline.setCreateTime(new Date());
            offlineService.addOfflineActivity(offline);
            rest = RestDataVo.OK(offline);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("新增活动失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/{id}/update"})
    public RestDataVo updateOfflineActivity(
            @PathVariable("id") Long id,
            @RequestBody OfflineActivity offline) {
        if ((offline.getStartTime() != null && offline.getEndTime() == null)
                || (offline.getStartTime() == null && offline.getEndTime() != null)) {
            return RestDataVo.ERROR("缺少开始/结束时间");
        }
        if (offline.getStartTime() != null && offline.getEndTime() != null) {
            if (offline.getStartTime().before(new Date())) {
                return RestDataVo.ERROR("线下活动开始时间不能早于当前时间");
            }
            if (offline.getEndTime().before(new Date()) || offline.getEndTime().before(offline.getStartTime())) {
                return RestDataVo.ERROR("线下活动结束时间不能早于当前/活动开始时间");
            }
        }
        RestDataVo rest = null;
        try {
            offlineService.editOfflineActivity(id, offline.getName(), offline.getPosition(), null, new Date(),
                    offline.getStartTime(), offline.getEndTime(), offline.getContent());
            rest = RestDataVo.OK("修改活动成功");
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("修改活动失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/{id}/remove"})
    public RestDataVo removeOfflineActivity(@PathVariable("id") Long id) {
        RestDataVo rest = null;
        try {
            offlineService.removeOfflineActivity(id);
            rest = RestDataVo.OK("删除活动成功");
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("删除活动失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/list"})
    public RestDataVo getOfflineActivityList(
//            @RequestParam(value = "name", required = false) String name,
//            @RequestParam(value = "position", required = false) String position,
//            @RequestParam(value = "status", required = false) Integer status,
            @RequestBody Map<String, String> map) {
        RestDataVo rest = new RestDataVo();
        String pageIndex = map.get("pageIndex");
        String pageSize = map.get("pageSize");
        PagingParam paging = new PagingParam();
        if (pageIndex != null) {
            paging.setPageIndex(Integer.parseInt(pageIndex));
        }
        if (pageSize != null) {
            paging.setPageSize(Integer.parseInt(pageSize));
        }
        String name = map.get("name");
        String position = map.get("position");
        String st = map.get("status");
        Integer status = null;
        if (st != null && st.trim().length() > 0) {
            status = Integer.parseInt(st);
        }
        paging = CommonUtils.validPageParam(paging);
//        Long userId = getUserId();
        try {
            Integer s = null;
            if (Objects.equals(status, OfflineActivityStatus.ACTIVITY_SIGNING.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_END.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_ING.value())) {
                s = status;
            }
            List<OfflineActivity> offlineList = offlineService.getOfflineActivityList(name, position, s, paging.getOrderBy(),
                        paging.getOrder(), paging.getOffset(), paging.getRows());
            int count = offlineService.getOfflineActivityCount(name, position, s);
            rest = RestDataVo.PAGE(offlineList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/list/calendar"})
    public RestDataVo getOfflineActivityListCalendar() {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            List<OfflineActivity> offlineList = offlineService.getOfflineActivityListCalendar();
            rest = RestDataVo.OK(offlineList);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/info/{id}"})
    public RestDataVo getOfflineActivityInfo(@PathVariable("id") Integer id) {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            OfflineActivity offline = offlineService.queryOfflineActivityById(id);
            rest = RestDataVo.OK(offline);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @GetMapping(value = {"/info/signup/{id}"})
    public RestDataVo getOfflineActivitySignUpInfo(@PathVariable("id") Long id) {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            OfflineActivitySignUp signup = signUpService.queryOfflineActivitySignUpById(id);
            rest = RestDataVo.OK(signup);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动报名详情成功");
        }
        return rest;
    }
    
    /**
     * 报名列表
     * @param offlineId
     * @param pageIndex
     * @param pageSize
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/list/signup"})
    public RestDataVo getOfflineActivitySignUpList(@RequestParam(value = "offlineId", required = false) Integer offlineId,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
//        Long userId = 1L;
        try {
            List<OfflineActivitySignUp> signup = signUpService.getOfflineActivitySignUpList(null, offlineId, null,
                    paging.getOffset(), paging.getRows());
            int count = signUpService.getOfflineActivitySignUpCount(null, offlineId, null);
            rest = RestDataVo.PAGE(signup, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动报名详情成功");
        }
        return rest;
    }
    
    @PostMapping(value = {"/audit/signup/{id}/{status}"})
    public RestDataVo getOfflineActivitySignUpInfo(@PathVariable("status") String status,
            @PathVariable("id") Long id) {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            Integer s = null;
            if (Objects.equals(status, "1")) {
                s = OfflineActivityStatus.SING_UP_AUDIT_PASS.value();
                //推送
            } else {
                s = OfflineActivityStatus.SING_UP_AUDIT_NOT_PASS.value();
                //推送
            }
            signUpService.editOfflineActivitySignUp(id, s, new Date());
            rest = RestDataVo.OK("审核成功");
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("审核活动报名成功");
        }
        return rest;
    }

}
